<template>
  <div class="container">
    <!-- 吸顶盒子的内容 -->
    <div class="sticky-box">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
        "
      >
        <div></div>
        <div style="display: flex; align-items: center">
          <a-select
            v-model:value="formData.isTop"
            style="width: 120px; margin-right: 15px"
            placeholder="置顶"
          >
            <a-select-option value="0">不置顶</a-select-option>
            <a-select-option value="1">文章置顶</a-select-option>
          </a-select>
          <a-select
            v-model:value="formData.isComment"
            style="width: 120px; margin-right: 15px"
            placeholder="评论"
          >
            <a-select-option value="0">可评论</a-select-option>
            <a-select-option value="1">不可评论</a-select-option>
          </a-select>
          <!-- 查询按钮 -->
          <a-button @click="add" style="margin-right: 20px" type="primary">
            {{ showType }}
          </a-button>
        </div>
      </div>
    </div>
    <!-- 表单的内容 -->
    <div class="form-data">
      <form>
        <a-form
          :model="formData"
          :label-col="{ style: { width: '80px' } }"
          :wrapper-col="{ span: 24 }"
        >
          <a-row>
            <a-col :span="24" style="text-align: right">
              <a-form-item
                label="文章标题"
                :rules="[{ required: true, message: '请输入文章标题!' }]"
              >
                <a-input
                  v-model:value="formData.articleTitle"
                  placeholder="请输入文章标题"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="24" style="text-align: right">
              <a-form-item
                label="文章描述"
                :rules="[{ required: false, message: '请输入文章描述!' }]"
              >
                <a-input
                  v-model:value="formData.description"
                  placeholder="请输入文章描述"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="6" style="text-align: right">
              <a-form-item
                label="预览图"
                :rules="[{ required: true, message: '请输入预览图!' }]"
              >
                <a-input
                  v-model:value="formData.articleCover"
                  placeholder="请输入预览图"
                />
              </a-form-item>
            </a-col>
            <a-col :span="2" style="text-align: right">
              <a-form-item label="">
                <a-upload
                  v-model:file-list="fileList"
                  name="image"
                  @change="handleChange"
                  class="avatar-uploader"
                  :show-upload-list="false"
                  :before-upload="beforeUpload"
                >
                  <a-button
                    style="background-color: #f0f0f0; margin-right: 22px"
                  >
                    图片上传
                    <vab-icon icon="file-upload-fill"></vab-icon>
                  </a-button>
                </a-upload>
              </a-form-item>
            </a-col>

            <a-col :span="8" style="text-align: left">
              <a-form-item
                label="菜单"
                :rules="[{ required: true, message: '请输入菜单!' }]"
              >
                <!-- 异步加载，修改存在bug已经废弃 -->
                <!-- <a-tree-select
                  v-model:value="formData.menuId"
                  tree-data-simple-mode
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="menuData"
                  placeholder="Please select"
                  :load-data="onLoadData"
                /> -->

                <a-tree-select
                  v-model:value="formData.menuId"
                  show-search
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择菜单"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="menuData"
                  :field-names="{
                    children: 'children',
                    label: 'name',
                    value: 'id',
                  }"
                  tree-node-filter-prop="name"
                ></a-tree-select>
              </a-form-item>
            </a-col>

            <a-col :span="8" style="text-align: left">
              <a-form-item
                label="文章标签"
                :rules="[{ required: true, message: '请输入文章标签!' }]"
              >
                <a-select
                  v-model:value="formData.tags"
                  mode="multiple"
                  show-search
                  allowClear="true"
                  style="width: 100%"
                  placeholder="Please select"
                  :options="tagsData"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  :field-names="{
                    label: 'name',
                    value: 'id',
                  }"
                  @search="handleSearchTags"
                ></a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="3" style="text-align: right">
              <a-form-item label="是否原创">
                <a-switch
                  v-model:checked="formData.type"
                  checkedValue="0"
                  unCheckedValue="1"
                  checked-children="是"
                  un-checked-children="否"
                />
              </a-form-item>
            </a-col>

            <a-col v-if="formData.type == 1" :span="7" style="text-align: left">
              <a-form-item
                label="原文链接"
                :rules="[{ required: false, message: '请输入原文链接!' }]"
              >
                <a-input
                  v-model:value="formData.originalUrl"
                  placeholder="请输入原文链接"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-if="formData.originalUrl != null && formData.originalUrl != ''"
              :span="8"
              style="text-align: left"
            >
              <a-form-item
                label="爬取规则"
                :rules="[{ required: false, message: '请选择爬取规则!' }]"
              >
                <a-select
                  v-model:value="formData.spider"
                  placeholder="请选择爬取规则"
                  show-search
                  allowClear="true"
                  :options="spiderData"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  :field-names="{
                    label: 'name',
                    value: 'id',
                  }"
                  @search="handleSearchSpider"
                  @change="handleChangeSpider"
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col
              v-if="formData.originalUrl != null && formData.originalUrl != ''"
              :span="6"
              style="padding-left: 20px"
            >
              <a-button @click="spiderArticle" type="primary">抓取</a-button>
            </a-col>
          </a-row>

          <a-tabs v-model:activeKey="activeKey">
            <a-tab-pane key="0">
              <template #tab>
                <span>
                  <apple-outlined />
                  文章
                </span>
              </template>

              <a-row>
                <a-col :span="24">
                  <a-form-item>
                    <a-radio-group
                      v-model:value="formData.textType"
                      button-style="solid"
                      @change="changeEdit"
                    >
                      <a-radio-button value="0">markdown编辑器</a-radio-button>
                      <a-radio-button value="1">
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;HTML编辑器&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                      </a-radio-button>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
              </a-row>

              <!-- markdown编辑器 -->
              <mavon-editor
                v-if="formData.textType != 1"
                ref="md"
                v-model="formData.articleContent"
                class="markdown-editor"
                @imgAdd="uploadImg"
                :toolbars="toolbars"
              ></mavon-editor>
              <!-- HTML编辑器 -->
              <editor
                v-if="formData.textType != 0"
                ref="tinymce"
                v-model="formData.articleContent"
                @input="
                  (val) => {
                    formData.articleContent = val
                  }
                "
              ></editor>
            </a-tab-pane>
            <a-tab-pane key="1">
              <template #tab>
                <span>
                  <android-outlined />
                  视频
                </span>
              </template>
              <video-upload
                @video-uploaded="handleVideoUploaded"
                :previewUrl="formData.videoPath"
              />
            </a-tab-pane>
            <a-tab-pane key="2">
              <template #tab>
                <span>
                  <android-outlined />
                  题目
                </span>
              </template>
              <question
                :key="questionKey"
                @question-update="handleUpdateQuestion"
                :_questions="questions"
              />
            </a-tab-pane>
          </a-tabs>
        </a-form>
      </form>
    </div>
  </div>
</template>
<script>
  import { add, get, update } from '@/api/article'
  import { getTagsTree } from '@/api/tags'
  import { getAllSpider, spiderArticle } from '@/api/spider'
  import { getMenuTree } from '@/api/menu'
  import { mavonEditor } from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'
  import toolbars from './toolbars'
  import { fileUpload } from '@/api/common'
  import VabIcon from '@/layout/vab-icon'
  import { message } from 'ant-design-vue'
  import { ref } from 'vue'
  import VideoUpload from './component/VideoUpload'
  import Question from './component/Question'
  import { Modal } from 'ant-design-vue'
  import Editor from './component/Tinymce'
  import TurndownService from 'turndown'
  const turndownService = new TurndownService()

  const menuData = ref([])

  export default {
    components: {
      mavonEditor,
      VabIcon,
      VideoUpload,
      Question,
      Editor,
    },
    data() {
      return {
        formData: {}, // 新增的数据
        toolbars: toolbars,
        tagsData: [], // 当前展示的tag
        allTagsData: [], // 全部tag
        spiderData: [], // 当前展示的规则
        allSpiderData: [], // 全部规则
        menuData: menuData, // 菜单列表
        activeKey: ref('0'), // 默认展示的页面
        questions: [
          {
            questionType: 1, // 试题类型 1 单选 2 多选 3 判断 4 填空
            statement: '', // 题干
            questionOptions: ['', '', ''], // 选项
            correctOptions: [], // 选中选项
            answers: '', //解释
          },
        ],
        articleId: null, // 修改的id
        showType: '创建', // 创建或者修改
        questionKey: 0, //用于重新渲染子组件
      }
    },
    created() {
      // 添加监听
      window.addEventListener('beforeunload', this.handleBeforeUnload)
    },
    beforeUnmount() {
      // 删除监听
      window.removeEventListener('beforeunload', this.handleBeforeUnload)
    },
    mounted() {
      const articleId = this.$route.params.id
      this.articleId = articleId
      this.init()
    },
    methods: {
      handleBeforeUnload(event) {
        // 表单的内容有值
        if (this.formData.articleTitle) {
          // Display a confirmation dialog
          event.returnValue =
            'You have unsaved changes. Are you sure you want to leave?'
          console.log(event.returnValue)
        }
      },
      // 爬取文章
      spiderArticle() {
        let _data = {
          id: this.formData.spider,
          url: this.formData.originalUrl,
        }
        spiderArticle(_data).then((data) => {
          this.formData.articleTitle = data.data.articleTitle
          this.formData.articleContent = data.data.articleContent
          this.formData.description = data.data.description
        })
      },
      // 更改文本内容方式的回调
      changeEdit(event) {
        console.log(event.target.value)
        if (event.target.value == 1) {
          // TODO 此处应该将markdown转成html
          this.formData.articleContent = this.$refs.md.d_render
        } else {
          // 将html代码转换成markdown
          this.formData.articleContent = turndownService.turndown(
            this.formData.articleContent
          )
        }
      },
      // 选择爬虫规则
      handleChangeSpider() {},
      // 处理题目更改
      handleUpdateQuestion(questions) {
        this.questions = questions
      },
      // 处理上传视频
      handleVideoUploaded(path) {
        this.formData.videoPath = path
      },
      // 搜索框搜索标签
      handleSearchTags(val) {
        this.tagsData = this.allTagsData.filter((tag) => {
          return tag.name.includes(val)
        })
      },
      // 搜索框搜索规则
      handleSearchSpider(val) {
        this.spiderData = this.allSpiderData.filter((spider) => {
          return spider.name.includes(val)
        })
      },
      // 搜索框搜索菜单
      handleSearchMenu(val) {
        console.log(val)
      },
      // 异步加载树节点。（已废弃）
      //   onLoadData(treeNode) {
      //     return new Promise((resolve) => {
      //       const { id } = treeNode.dataRef
      //       this.getMenuTree(id)
      //       resolve(true)
      //     })
      //   },
      //   添加或者修改
      add() {
        this.formData.contentType = this.activeKey
        let title = '文章'
        if (this.formData.contentType == 1) {
          title = '视频'
        }
        if (this.formData.contentType == 2) {
          title = '题目'
        }
        Modal.confirm({
          title: 'Confirm',
          content:
            '当前' +
            this.showType +
            '的是' +
            title +
            ',确定要' +
            this.showType +
            '吗？',
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            // 如果添加的类型是题目
            if (this.formData.contentType == 2) {
              this.formData.questions = this.questions
            }
            // 存在为修改
            if (this.articleId && this.articleId != ':id') {
              this.formData.id = this.articleId
              update(this.formData).then((data) => {
                console.log(data)
                this.articleId = null
                this.showType = '创建'
                // 添加成功清除表单
                this.formData = {
                  isTop: '0',
                  isComment: '0',
                  type: '0',
                  status: '1',
                  textType: '0',
                }
                this.questions = [
                  {
                    questionType: 1, // 试题类型 1 单选 2 多选 3 判断 4 填空
                    statement: '', // 题干
                    questionOptions: ['', '', ''], // 选项
                    correctOptions: [], // 选中选项
                    answers: '', //解释
                  },
                ]
                this.reloadComponent()
              })
            } else {
              add(this.formData).then((data) => {
                console.log(data)
                // 添加成功清除表单
                this.formData = {
                  isTop: '0',
                  isComment: '0',
                  type: '0',
                  status: '1',
                  textType: '0',
                }
                this.questions = [
                  {
                    questionType: 1, // 试题类型 1 单选 2 多选 3 判断 4 填空
                    statement: '', // 题干
                    questionOptions: ['', '', ''], // 选项
                    correctOptions: [], // 选中选项
                    answers: '', //解释
                  },
                ]
                this.reloadComponent()
              })
            }
          },
        })
      },
      reloadComponent() {
        this.questionKey += 1
      },
      init() {
        // 获取爬虫规则
        getAllSpider({}).then((data) => {
          console.log(data)
          this.allSpiderData = data.data
          this.spiderData = data.data
        })
        // 请求查询标签
        getTagsTree({}).then((data) => {
          console.log(data)
          this.allTagsData = data.data
          this.tagsData = data.data
        })
        // 懒加载查询菜单(已废弃)
        // getMenuTreeList({ id: 0 }).then((data) => {
        //   this.menuData = ref(data.data)
        // })
        // 获取全量菜单树
        this.getMenuAllTree()
        // 存在id为创建
        if (this.articleId && this.articleId != ':id') {
          this.showType = '修改'
          get({ id: this.articleId }).then((data) => {
            this.formData = data.data
            // ant design限制只能使用字符串,此处需要重新赋值一下
            this.formData.isTop = this.formData.isTop + ''
            this.formData.isComment = this.formData.isComment + ''
            this.formData.type = this.formData.type + ''
            this.formData.status = this.formData.status + ''
            this.formData.textType = this.formData.textType + ''
            // 显示为对应的内容
            this.activeKey = ref(data.data.contentType + '')
            // 题目需要单独赋值
            if (data.data.contentType == 2) {
              this.questions = data.data.questions
            }
          })
          // 不存在id为新增
        } else {
          this.formData = {
            isTop: '0',
            isComment: '0',
            type: '0',
            status: '1',
            textType: '0',
          }
        }
      },
      getMenuAllTree(name) {
        getMenuTree({ name: name == undefined ? '' : name }).then((data) => {
          if (data.data) {
            console.log('菜单')
            console.log(data.data)
            this.menuData = data.data
          }
        })
      },
      // 异步查询子菜单。(已废弃)
      //   getMenuTree(id) {
      //     getMenuTreeList({ id: id }).then((data) => {
      //       if (data.data) {
      //         for (let index = 0; index < data.data.length; index++) {
      //           const element = data.data[index]
      //           this.menuData.push(element)
      //         }
      //       }
      //     })
      //   },
      // 上传图片
      beforeUpload(file) {
        const formData = new FormData()
        formData.append('image', file)
        formData.append('label', 'article')
        fileUpload(formData).then((data) => {
          this.formData.articleCover = data.data
        })
        console.log(file)
        return true
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true
        }
        if (info.file.status === 'done') {
          // 上传完成后的操作
          this.loading = false

          // 从后台返回的响应中获取文件访问路径
          const response = info.file.response
          if (response && response.url) {
            this.formData.avatar = response.url
          }
        }
        if (info.file.status === 'error') {
          // 上传出错时的操作
          this.loading = false
        }
      },
      // 富文本编辑上传图片
      uploadImg(filename, file) {
        const formData = new FormData()
        formData.append('image', file)
        formData.append('label', 'article')
        fileUpload(formData).then((data) => {
          message.success('上传成功')
          this.$refs.md.$img2Url(filename, data.data)
        })
      },
    },
  }
</script>
<style>
  /* styles.css */
  .container {
    width: 100%;
    padding: 10px;
  }

  .sticky-box {
    position: sticky;
    top: 0;
    width: 100%; /* 与父容器宽度相同 */
    background-color: #f0f0f0; /* 使用十六进制颜色代码 */
    padding: 15px 10px 5px 0px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    z-index: 100;
    border-radius: 10px;
    margin-bottom: 20px;
  }

  .markdown-editor {
    min-height: 500px;
    z-index: 0;
  }
  .html-editor {
    min-height: 500px;
    z-index: 0;
  }
</style>
